

#include "gd32w51x.h"
#include "FreeRTOS.h"
#include "task.h"

#include "BSP.h"
#include "WatchDog.h"
#include "Log.h"
#include "Debug.h"

#include <Reader/ReaderBLE.h>

#include <Modules/BLE/BLE_IF.h>
#include <Modules/BLE/BLE.h>
#include <Reader.h>
#include "config/config3.h"

#include "fun.h"
#include "simple_protocol.h"
#include "task_config.h"

xTaskHandle funTaskHandle;
xTaskHandle sptlTaskHandle;

#ifdef _TEST_

#define TEST_TASK_STACK_SIZE	 (configMINIMAL_STACK_SIZE + 1024)
#define TEST_TASK_PRIORITY		(tskIDLE_PRIORITY + 3)

//	static StaticTask_t test_task_buf;
//	static StackType_t test_task_stack_buf[TEST_TASK_STACK_SIZE];

xTaskHandle testTaskHandle;

int test_main(void);

static void test_task(void* params){
	vTaskDelay(100);
	int ret = test_main();
	LOG_W("test exit(%d)!", ret);
	vTaskDelete(NULL);
}

#endif


#define HZ_1M	(100*10000U)

static void print_sys_info(void){
	TRACE_D("CK_SYS = %u MHz", rcu_clock_freq_get(CK_SYS)/HZ_1M);
	TRACE_D("CK_AHB = %u MHz", rcu_clock_freq_get(CK_AHB)/HZ_1M);
	TRACE_D("CK_APB1 = %u MHz", rcu_clock_freq_get(CK_APB1)/HZ_1M);
	TRACE_D("CK_APB2 = %u MHz", rcu_clock_freq_get(CK_APB2)/HZ_1M);
	TRACE_D("CK_USART0 = %u MHz", rcu_clock_freq_get(CK_USART0)/HZ_1M);
	TRACE_D("CK_USART2 = %u MHz", rcu_clock_freq_get(CK_USART2)/HZ_1M);
	TRACE_D("CK_I2C0 = %u MHz", rcu_clock_freq_get(CK_I2C0)/HZ_1M);
}

void startTask(void *arg)
{
	LOG_CTRL(RTT_CTRL_CLEAR);
	print_sys_info();
	BSP_Init();
	config3_init();
	Reader_NFC_Setup();	
 	Reader_NFC_Init(); 	

#ifdef _TEST_
 	BLE_IF_Init();
 	Reader_BLE_Init();
	xTaskCreate(test_task, "testTask", configMINIMAL_STACK_SIZE + 1024, NULL, tskIDLE_PRIORITY + 3, &testTaskHandle);
#else
 	xTaskCreate(fun_task, "funTask", FUN_TASK_STACK_SIZE, NULL, FUN_TASK_PRIORITY, &funTaskHandle);
 	xTaskCreate(simpleProtocol_task, "sptlTask", SPTL_TASK_STACK_SIZE, NULL, SPTL_TASK_PRIORITY, &sptlTaskHandle);
#endif
	
 	vTaskDelete(NULL);
}

int main(void)
{
	nvic_priority_group_set(NVIC_PRIGROUP_PRE4_SUB0);	
#ifdef NDEBUG
	WatchDog_Start(8000);
#endif
	xTaskCreate(startTask, "startTask", 1024*2, NULL, 1, NULL);
	
	vTaskStartScheduler();
	configASSERT(0);
}


